package netty.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Component
public class NettyClient {
    private EventLoopGroup group;
    private Channel channel;
    private final String HOST = "localhost";
    private final int PORT = 8080;

    @PostConstruct
    public void connect() throws InterruptedException {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                // 超时检测：所有类型超时设置为 5 秒
                                .addLast(new IdleStateHandler(0, 0, 5, TimeUnit.SECONDS))
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new ClientHandler());
                    }
                });
        channel = bootstrap.connect(HOST, PORT).sync().channel();
    }

    public void sendMessage(String msg) {
        channel.writeAndFlush(msg);
    }

    @PreDestroy
    public void disconnect() {
        group.shutdownGracefully();
    }
}